//
//  ProjectListController.swift
//  QualityControlSystem
//
//  Created by Daniel Hu on 1/5/17.
//  Copyright © 2017 com.mask. All rights reserved.
//

import Foundation
import MJRefresh
import MJExtension
import SVProgressHUD

class ProjectListController: UITableViewController {
    
    //MARK: - Properties
    
    var projects = [ProjectInfo]()
    var parentNavigationController: UINavigationController?
    var cur_page: Int?
    var max_page: Int?
    let type: Int
    
    //MARK: - ViewController lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureTableView()
        loadNewData()
    }
    
    init(type: Int) {
        self.type = type
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configureTableView() {
        // refresh header
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        header?.lastUpdatedTimeLabel.isHidden = true
        tableView.mj_header = header
        
        // load more footer
        tableView.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        tableView.tableFooterView = UIView()
        tableView.register(ProjectInfoCell.self, forCellReuseIdentifier: "projectInfoCell")
    }
    
    //MARK: - Load data
    
    func loadNewData() {
        projects.removeAll()
        HTTPRequest.projectListWith(type: type, page: 1, completion: { response in
            self.tableView.mj_header.endRefreshing()
            if let response = response {
                self.cur_page = response["cur_page"] as? Int
                self.max_page = response["max_page"] as? Int
                for project in response["item"] as! [AnyObject] {
                    let foo = ProjectInfo.mj_object(withKeyValues: project)
                    self.projects.append(foo!)
                }
            }
            self.tableView.reloadData()
        })
    }
    
    func loadMoreData() {
        if cur_page! < max_page! {
            HTTPRequest.projectListWith(type: type, page: cur_page! + 1, completion: { response in
                self.tableView.mj_footer.endRefreshing()
                if let response = response {
                    self.cur_page = response["cur_page"] as? Int
                    self.max_page = response["max_page"] as? Int
                    for project in response["item"] as! [AnyObject] {
                        let foo = ProjectInfo.mj_object(withKeyValues: project)
                        self.projects.append(foo!)
                    }
                }
                self.tableView.reloadData()
            })
        } else {
            self.tableView.mj_footer.endRefreshing()
        }
    }
    
    //MARK: - UITableViewDataSource
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return projects.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "projectInfoCell", for: indexPath) as! ProjectInfoCell
        cell.accessoryType = .disclosureIndicator
        cell.data = projects.first
        return cell
    }
    
    //MARK: - UITableViewDelegate
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let project = projects[indexPath.row]
        let projectDetail = ProjectDetailController(id: project.id!)
        parentNavigationController!.pushViewController(projectDetail, animated: true)
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return Constant.projectCellHeight
    }
}
